package com.wenju.wjvideoplay;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.CheckedTextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.wenju.wjvideoplay.bean.CloudHistoryPlayBackBean;
import com.wenju.wjvideoplay.util.TimestampToTimeDate;
import com.wenju.wjvideoplay.util.WenMediaPlayerUtil;
import com.wenju.wjvideoplay.view.TimeRuleView;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


public class CloudCameraHistoryPlaybackActivity extends AppCompatActivity {
    private RelativeLayout wTopRll;

    private final int MODE_PORTRAIT = 0;//竖屏模式
    private final int MODE_LANDSPACE = 1;//横屏模式
    private int viewMode = MODE_PORTRAIT;//横竖屏记录
    //时间轴
    private TimeRuleView wTimeRuleView;
    private View timeRuleViewTransparent;
    private TimeRuleView wFullScreenTimeRuleView;
    //全屏
    private ImageView wIvHistoryPlaybackFullScreen;
    //音频
    private static ImageView wImSound;
    //倍速
    private CheckedTextView wCtvPlaybackSpeed;
    //倍速选择布局
    private RelativeLayout wRlPlaybackSpeed;
    //倍速
    private TextView wPlaybackSpeed1, wPlaybackSpeed2, wPlaybackSpeed3, wPlaybackSpeed4;
    private float mDoubleSpeed = 1;

    private TextureView textureView;
    private TextView wFrostedBoard;
    private TextView wFrostedBoard2;

    private ImageButton wImbPlay;
    private ProgressBar wVideoProgressBar;//视频加载进度条
    private ArrayList<String> mVideoListQueue = new ArrayList<>();//视频播放源集合
    private WenMediaPlayerUtil wenMediaPlayerUtil;//视频播放器
    private Timer timer;//定义一个计时器，每隔100ms更新一次进度条
    private TimerTask task;//计时器所执行的任务

    private List<TimeRuleView.TimePart> mAlarmlist = new ArrayList<>();//报警时间集合
    private List<TimeRuleView.TimePart> mFUlllist = new ArrayList<>();//全时时间集合
    private List<TimeRuleView.TimePart> mAlllist = new ArrayList<>();//全部时间集合
    public int mRuleTimeValue;//时间尺移动到的时间

    private ImageView wImHistoryDownload;
    private int screenWidth;

    //全屏控件
    private LinearLayout wLyRightFullScreenFunctionBtn;
    private RelativeLayout wRLFullScreenTimeRule;
    private LinearLayout wLyCtvPullScreenPlaybackSpeed;
    private LinearLayout wLyFullScreenPlaybackSpeed;
    private ImageButton wImbFullScreenSound;
    private ImageButton wImbFullScreenPlay;
    private ImageButton wImbFullScreenDown;
    private CheckedTextView wCtvPullScreenPlaybackSpeed;
    private TextView wFullScreenPlaybackSpeed1, wFullScreenPlaybackSpeed2, wFullScreenPlaybackSpeed3, wFullScreenPlaybackSpeed4;


    private ArrayList<CloudHistoryPlayBackBean> mVideoDateList = new ArrayList<>();

    private final static int FULL_SCREEN_WEIGHT = 1;
    private boolean mAgainTag;//3秒内再次点击字节移回布局
    private HideHandler mHideHandler;
    private LinearLayout wLyDownloadView;
    private TextView wTvDownloadCount, wTvCancelDownload;
    private InputStream is;
    private OutputStream os;
    private boolean isCancle;
    private String dirName, fileName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloud_camera_history_playback);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕唤醒
        initView();
    }

    public void initView() {
        //照片路径
        dirName = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator;
        File file = new File(dirName);
        // 文件夹不存在时创建
        if (!file.exists()) {
            file.mkdir();
        }
        wLyDownloadView = findViewById(R.id.ly_download_view);
        wTvDownloadCount = findViewById(R.id.tv_download_count);
        wTvCancelDownload = findViewById(R.id.tv_cancel_download);
        wTvCancelDownload.setOnClickListener(onClickListener);


        //自定义导航栏
        wTopRll = findViewById(R.id.top_rll);
        TextView wTvBack = findViewById(R.id.tv_left);
        wTvBack.setOnClickListener(onClickListener);
        TextView wTvTitle = findViewById(R.id.tv_title);
        wTvTitle.setText(R.string.str_paly_video);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int screenWidth = metrics.widthPixels;

        wTimeRuleView = findViewById(R.id.time_rule_view);
        timeRuleViewTransparent = findViewById(R.id.time_rule_view_transparent);
        wFullScreenTimeRuleView = findViewById(R.id.full_screen_time_rule_view);
        wImSound = findViewById(R.id.im_sound);
        wCtvPlaybackSpeed = findViewById(R.id.ctv_playback_speed);
        wRlPlaybackSpeed = findViewById(R.id.rl_playback_speed);
        wPlaybackSpeed1 = findViewById(R.id.playback_speed_1);
        wPlaybackSpeed2 = findViewById(R.id.playback_speed_2);
        wPlaybackSpeed3 = findViewById(R.id.playback_speed_3);
        wPlaybackSpeed4 = findViewById(R.id.playback_speed_4);
        wImbPlay = findViewById(R.id.imb_play);
        wImSound.setOnClickListener(onClickListener);
        wCtvPlaybackSpeed.setOnClickListener(onClickListener);
        wPlaybackSpeed1.setOnClickListener(onClickListener);
        wPlaybackSpeed2.setOnClickListener(onClickListener);
        wPlaybackSpeed3.setOnClickListener(onClickListener);
        wPlaybackSpeed4.setOnClickListener(onClickListener);
        wImbPlay.setOnClickListener(onClickListener);
        wIvHistoryPlaybackFullScreen = findViewById(R.id.iv_history_playback_full_screen);
        wIvHistoryPlaybackFullScreen.setOnClickListener(onClickListener);
        textureView = findViewById(R.id.texture_view);
        wFrostedBoard = findViewById(R.id.tv_frosted_board);
        wFrostedBoard2 = findViewById(R.id.tv_frosted_board2);
        wVideoProgressBar = findViewById(R.id.video_progress_bar);
        wImHistoryDownload = findViewById(R.id.im_history_download);
        wImHistoryDownload.setOnClickListener(onClickListener);
        textureView.setOnClickListener(onClickListener);

        //全屏控件
        wLyRightFullScreenFunctionBtn = findViewById(R.id.ly_right_full_screen_function_btn);
        wRLFullScreenTimeRule = findViewById(R.id.rl_full_screen_time_rule);
        wLyCtvPullScreenPlaybackSpeed = findViewById(R.id.ly_ctv_pull_screen_playback_speed);
        wLyFullScreenPlaybackSpeed = findViewById(R.id.ly_full_screen_playback_speed);
        wImbFullScreenSound = findViewById(R.id.imb_full_screen_sound);
        wImbFullScreenPlay = findViewById(R.id.imb_full_screen_play);
        wImbFullScreenDown = findViewById(R.id.imb_full_screen_down);
        ImageButton WImbFullScreenDisplay = findViewById(R.id.imb_full_screen_display);
        wCtvPullScreenPlaybackSpeed = findViewById(R.id.ctv_pull_screen_playback_speed);
        wFullScreenPlaybackSpeed1 = findViewById(R.id.full_screen_playback_speed_1);
        wFullScreenPlaybackSpeed2 = findViewById(R.id.full_screen_playback_speed_2);
        wFullScreenPlaybackSpeed3 = findViewById(R.id.full_screen_playback_speed_3);
        wFullScreenPlaybackSpeed4 = findViewById(R.id.full_screen_playback_speed_4);

        wImbFullScreenSound.setOnClickListener(onClickListener);
        wImbFullScreenPlay.setOnClickListener(onClickListener);
        wImbFullScreenDown.setOnClickListener(onClickListener);
        WImbFullScreenDisplay.setOnClickListener(onClickListener);
        wCtvPullScreenPlaybackSpeed.setOnClickListener(onClickListener);
        wFullScreenPlaybackSpeed1.setOnClickListener(onClickListener);
        wFullScreenPlaybackSpeed2.setOnClickListener(onClickListener);
        wFullScreenPlaybackSpeed3.setOnClickListener(onClickListener);
        wFullScreenPlaybackSpeed4.setOnClickListener(onClickListener);


        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
            wCtvPlaybackSpeed.setVisibility(View.GONE);
            wCtvPullScreenPlaybackSpeed.setVisibility(View.GONE);
        }
        //竖屏视屏播放宽高
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, (int) (screenWidth / 1.8));
        textureView.setLayoutParams(layoutParams);
        wFrostedBoard.setLayoutParams(layoutParams);
        wFrostedBoard2.setLayoutParams(layoutParams);
        wTimeRuleView.setOnTimeChangedListener(onTimeChangedListener);
        wFullScreenTimeRuleView.setOnTimeChangedListener(onTimeChangedListener);
        wTimeRuleView.setOnTouchListener(onTouchListener);
        wFullScreenTimeRuleView.setOnTouchListener(onTouchListener);
        timeRuleViewTransparent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Toast.makeText(CloudCameraHistoryPlaybackActivity.this, getString(R.string.open_mediaplayer_toast),Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        initData();
    }

    public void initData() {
        mHideHandler = new HideHandler();
        //预获取数据
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        screenWidth = metrics.widthPixels;

        wenMediaPlayerUtil = new WenMediaPlayerUtil(CloudCameraHistoryPlaybackActivity.this);
        wenMediaPlayerUtil.setTextureView(textureView);
        wenMediaPlayerUtil.setWjSurfaceTextureAvailable(new WenMediaPlayerUtil.onWjSurfaceTextureAvailable() {
            @Override
            public void onWjSurfaceTextureAvailable() {
                addDate();
            }
        });
    }

    //进度尺刷新
    private void TimerRuleRefresh() {
        timer = new Timer();
        task = new TimerTask() {
            public void run() {
                if (wenMediaPlayerUtil != null) {
                    if (wenMediaPlayerUtil.getIsEndPlay()) {
                        timer.cancel();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                wFrostedBoard.setVisibility(View.GONE);
                                wVideoProgressBar.setVisibility(View.GONE);
                                wFrostedBoard2.setVisibility(View.VISIBLE);
                                wFrostedBoard2.setText(R.string.video_finished_playing);
                            }
                        });
                        wenMediaPlayerUtil.onDestoryMediaplayer();
                    } else if (wenMediaPlayerUtil.getIsReadyPlay() && wenMediaPlayerUtil.getMediaPlayer() != null) {
                        try {
                            if (wenMediaPlayerUtil.getMediaPlayer().isPlaying()) {
                                if (mAlllist.size() > 0&&mAlarmlist.size()>wenMediaPlayerUtil.getMediaPlayerIndex()) {
                                    Log.d("CurrentPosition", wenMediaPlayerUtil.getMediaPlayer().getCurrentPosition() / 1000 + "");
                                    wTimeRuleView.setCurrentTime((int) (mAlllist.get(wenMediaPlayerUtil.getMediaPlayerIndex()).startTime + wenMediaPlayerUtil.getMediaPlayer().getCurrentPosition() / 1000));
                                    wFullScreenTimeRuleView.setCurrentTime((int) (mAlllist.get(wenMediaPlayerUtil.getMediaPlayerIndex()).startTime + wenMediaPlayerUtil.getMediaPlayer().getCurrentPosition() / 1000));
                                }
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        new Handler().postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                wVideoProgressBar.setVisibility(View.GONE);
                                                wFrostedBoard.setVisibility(View.GONE);
                                            }
                                        }, 1000);    //延时1s执行
                                    }
                                });
                                if (wenMediaPlayerUtil != null) {
                                    if (wImSound.isSelected()) {
                                        wenMediaPlayerUtil.getMediaPlayer().setVolume(0, 0);
                                    } else {
                                        wenMediaPlayerUtil.getMediaPlayer().setVolume(1, 1);
                                    }
                                }

                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !wImbPlay.isSelected()) {
                                    wenMediaPlayerUtil.getMediaPlayer().setSpeed(mDoubleSpeed);
                                    if (mDoubleSpeed != 1) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                wImSound.setSelected(true);
                                                wImbFullScreenSound.setSelected(true);
                                            }
                                        });
                                    }
                                }
                            }
                        } catch (IllegalStateException ignored) {

                        }
                    }
                }
            }
        };
        timer.schedule(task, 0, 500);//0秒后执行，每隔500ms执行一次
    }

    /**
     * 进度尺时间监听
     */
    private long mTimeLast;
    private TimeRuleView.OnTimeChangedListener onTimeChangedListener = new TimeRuleView.OnTimeChangedListener() {
        @Override
        public void onTimeChanged(View v, int newTimeValue) {
            switch (v.getId()) {
                case R.id.time_rule_view:
                case R.id.full_screen_time_rule_view:
                    mRuleTimeValue = newTimeValue;
                    if (wFrostedBoard2.getVisibility() == View.GONE) {
                        wFrostedBoard2.setVisibility(View.VISIBLE);
                        wFrostedBoard2.setText(R.string.current_time_no_video);
                        wImbPlay.setEnabled(false);
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                wVideoProgressBar.setVisibility(View.GONE);
                            }
                        }, 1000);    //延时1s执
                    }

                    //遍历所有视频时间数据，确定进度尺播放视频
                    for (int i = 0; i < mVideoDateList.size(); i++) {
                        int startTime = TimestampToTimeDate.getStringDateToMillisecond(mVideoDateList.get(i).getStartDate());
                        int endTime = TimestampToTimeDate.getStringDateToMillisecond(mVideoDateList.get(i).getEndDate());

                        //判断是否在录像时间内
                        if (mRuleTimeValue > startTime && mRuleTimeValue < endTime) {
                            wVideoProgressBar.setVisibility(View.VISIBLE);
                            wFrostedBoard.setVisibility(View.VISIBLE);
                            wFrostedBoard2.setVisibility(View.GONE);
                            wImbPlay.setEnabled(true);
                            if (wenMediaPlayerUtil.getMediaPlayerIndex() == i) {
                                if (wenMediaPlayerUtil.getIsReadyPlay()) {
                                    wenMediaPlayerUtil.getMediaPlayer().start();
                                    wenMediaPlayerUtil.getMediaPlayer().seekTo((mRuleTimeValue - startTime) * 1000);
                                }
                            } else {
                                //过三秒未播放，开始播放
                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                       if(!isDown){
                                           if(wenMediaPlayerUtil!=null&&wenMediaPlayerUtil.getMediaPlayer()!=null){
                                               if(!wenMediaPlayerUtil.getMediaPlayer().isPlaying()){
                                                   wenMediaPlayerUtil.getMediaPlayer().start();
                                                   TimerRuleRefresh();
                                                   wFrostedBoard2.setVisibility(View.GONE);
                                               }
                                           }
                                       }
                                    }
                                }, 1000);    //延时1s执行
                                //防止暴力滑动
                                if (System.currentTimeMillis() - mTimeLast < 200) {
                                    return;
                                }
                                mTimeLast = System.currentTimeMillis();
                                wenMediaPlayerUtil.onDestoryMediaplayer();
                                wenMediaPlayerUtil.setTextureView(textureView);
                                wenMediaPlayerUtil.setMediaPlayerIndex(i);
                                wenMediaPlayerUtil.initFirstPlayer((mRuleTimeValue - TimestampToTimeDate.getStringDateToMillisecond(mVideoDateList.get(i).getStartDate())) * 1000, mVideoListQueue);
                                wVideoProgressBar.setVisibility(View.VISIBLE);
                                wFrostedBoard.setVisibility(View.VISIBLE);
                                TimerRuleRefresh();
                            }
                        } else {
                            if(wenMediaPlayerUtil.getMediaPlayer()!=null){
                                timer.cancel();
                                wenMediaPlayerUtil.getMediaPlayer().pause();
                            }
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            wVideoProgressBar.setVisibility(View.GONE);
                                            wFrostedBoard.setVisibility(View.GONE);
                                        }
                                    }, 1000);    //延时1s执行
                                }
                            });
                        }
                    }
                    break;
            }
        }
    };


    private boolean isDown;
    private AudioManager mAudioManager = null;
    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (v.getId()) {
                case R.id.time_rule_view:
                case R.id.full_screen_time_rule_view:
                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            isDown = true;
                            if (timer != null) {
                                timer.cancel();
                            }
                            if (wenMediaPlayerUtil.getIsReadyPlay() && wenMediaPlayerUtil.getMediaPlayer() != null) {
                                wenMediaPlayerUtil.getMediaPlayer().pause();
                            }
                            break;
                        case MotionEvent.ACTION_UP:
                            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
                            mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_MUTE , 0);//静音
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if(!isDown){
                                        TimerRuleRefresh();
                                        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_UNMUTE, 0);//取消静音
                                    }
                                }
                            }, 2000);
                            if (wenMediaPlayerUtil.getIsReadyPlay() && wenMediaPlayerUtil.getMediaPlayer() != null) {
                                wenMediaPlayerUtil.getMediaPlayer().start();
                            }
                            isDown = false;
                            break;
                    }
                    break;
            }
            return false;
        }
    };


    /**
     * 点击事件
     */
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_left:
                    finish();
                    break;
                case R.id.iv_history_playback_full_screen:
                case R.id.imb_full_screen_display:
                    screenDisplay();
                    break;
                case R.id.im_sound:
                case R.id.imb_full_screen_sound:
                    if (wImSound.isSelected()) {
                        wImSound.setSelected(false);
                        wImbFullScreenSound.setSelected(false);
                    } else {
                        wImSound.setSelected(true);
                        wImbFullScreenSound.setSelected(true);
                    }
                    break;
                case R.id.ctv_playback_speed:
                case R.id.ctv_pull_screen_playback_speed:
                    if (wCtvPlaybackSpeed.isChecked()) {
                        wCtvPlaybackSpeed.setChecked(false);
                        wCtvPullScreenPlaybackSpeed.setChecked(false);
                        if (v.getId() == R.id.ctv_playback_speed) {
                            wRlPlaybackSpeed.setVisibility(View.GONE);
                        } else {
                            wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                        }
                    } else {
                        wCtvPlaybackSpeed.setChecked(true);
                        wCtvPullScreenPlaybackSpeed.setChecked(true);
                        if (v.getId() == R.id.ctv_playback_speed) {
                            wRlPlaybackSpeed.setVisibility(View.VISIBLE);
                        } else {
                            wLyFullScreenPlaybackSpeed.setVisibility(View.VISIBLE);
                        }
                        switch ((int) mDoubleSpeed) {
                            case (int) 0.5:
                                wPlaybackSpeed1.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed1.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wFullScreenPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                break;
                            case 1:
                                wPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed2.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed2.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wFullScreenPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                break;
                            case 2:
                                wPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed3.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed3.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wFullScreenPlaybackSpeed4.setTextColor(getResources().getColor(R.color.color_ffffff));
                                break;
                            case 4:
                                wPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wPlaybackSpeed4.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                wFullScreenPlaybackSpeed1.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed2.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed3.setTextColor(getResources().getColor(R.color.color_ffffff));
                                wFullScreenPlaybackSpeed4.setTextColor(getResources().getColor(R.color.colorPrimaryDark));
                                break;
                        }
                    }
                    break;
                case R.id.imb_play:
                case R.id.imb_full_screen_play:
                    if (wenMediaPlayerUtil.getMediaPlayer().isPlaying()) {
                        wenMediaPlayerUtil.getMediaPlayer().pause();
                        timeRuleViewTransparent.setVisibility(View.VISIBLE);
                        wImbPlay.setSelected(true);
                        wImbFullScreenPlay.setSelected(true);
                    } else {
                        wenMediaPlayerUtil.getMediaPlayer().start();
                        timeRuleViewTransparent.setVisibility(View.GONE);
                        wImbPlay.setSelected(false);
                        wImbFullScreenPlay.setSelected(false);
                    }
                    break;
                case R.id.tv_frosted_board:
                    if (!wFrostedBoard.getText().equals("")) {
                        wFrostedBoard.setVisibility(View.GONE);
                        wenMediaPlayerUtil.setMediaPlayerIndex(0);
                        wenMediaPlayerUtil.initFirstPlayer(0, mVideoListQueue);
                        TimerRuleRefresh();
                    }
                    break;
                case R.id.imb_full_screen_snapshot:
                    saveBitmap(textureView.getBitmap(),System.currentTimeMillis()+"wj.png");
                    break;
                case R.id.playback_speed_1:
                case R.id.full_screen_playback_speed_1:
                    mDoubleSpeed = (float) 0.5;
                    wCtvPlaybackSpeed.setText("x0.5");
                    wCtvPullScreenPlaybackSpeed.setText("x0.5");
                    wRlPlaybackSpeed.setVisibility(View.GONE);
                    wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                    wCtvPlaybackSpeed.setChecked(false);
                    break;
                case R.id.playback_speed_2:
                case R.id.full_screen_playback_speed_2:
                    mDoubleSpeed = 1;
                    wCtvPlaybackSpeed.setText("x1");
                    wCtvPullScreenPlaybackSpeed.setText("x1");
                    wRlPlaybackSpeed.setVisibility(View.GONE);
                    wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                    wCtvPlaybackSpeed.setChecked(false);
                    break;
                case R.id.playback_speed_3:
                case R.id.full_screen_playback_speed_3:
                    mDoubleSpeed = 2;
                    wCtvPlaybackSpeed.setText("x2");
                    wCtvPullScreenPlaybackSpeed.setText("x2");
                    wRlPlaybackSpeed.setVisibility(View.GONE);
                    wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                    wCtvPlaybackSpeed.setChecked(false);
                    break;
                case R.id.playback_speed_4:
                case R.id.full_screen_playback_speed_4:
                    mDoubleSpeed = 4;
                    wCtvPlaybackSpeed.setText("x4");
                    wCtvPullScreenPlaybackSpeed.setText("x4");
                    wRlPlaybackSpeed.setVisibility(View.GONE);
                    wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                    wCtvPlaybackSpeed.setChecked(false);
                    break;
                case R.id.texture_view:
                    if (MODE_LANDSPACE == viewMode) {
                        if (mAgainTag) {
                            endHideTimer();
                            mHideHandler.obtainMessage(FULL_SCREEN_WEIGHT).sendToTarget();
                        } else {
                            //上移动画
                            TranslateAnimation moveUpAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 2.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                            moveUpAnimation.setDuration(350);
                            //左移动画
                            TranslateAnimation moveLeftAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 2.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                            moveLeftAnimation.setDuration(350);
                            wLyRightFullScreenFunctionBtn.setVisibility(View.VISIBLE);
                            wRLFullScreenTimeRule.setVisibility(View.VISIBLE);
                            wLyCtvPullScreenPlaybackSpeed.setVisibility(View.VISIBLE);

                            wLyRightFullScreenFunctionBtn.setAnimation(moveLeftAnimation);
                            wRLFullScreenTimeRule.setAnimation(moveUpAnimation);
                            wLyCtvPullScreenPlaybackSpeed.setAnimation(moveUpAnimation);

                            startHideTimer();
                            mAgainTag = true;
                        }
                    }
                    break;
                case R.id.im_history_download:
                case R.id.imb_full_screen_down:
                    onDownload();
                    break;
                case R.id.tv_cancel_download:
                    wLyDownloadView.setVisibility(View.GONE);
                    Toast.makeText(CloudCameraHistoryPlaybackActivity.this, R.string.cancel_download, Toast.LENGTH_LONG).show();
                    isCancle = true;
                    break;
                default:
            }
        }
    };


    /**
     * 跳转到本页的方法
     */

    public static void start(Context context) {
        Intent intent = new Intent(context, CloudCameraHistoryPlaybackActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        (context).startActivity(intent);
    }

    //横竖屏切换
    private void screenDisplay() {
        if (viewMode == MODE_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            viewMode = MODE_LANDSPACE;
        } else {
            viewMode = MODE_PORTRAIT;
        }

        //控件重新绘制
        if (viewMode == MODE_PORTRAIT) {
            //显示虚拟按键
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                View decorView = getWindow().getDecorView();
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                        View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                decorView.setSystemUiVisibility(option);
                this.getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }

            //竖屏视屏播放宽高
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, (int) (screenWidth / 1.8));
            textureView.setLayoutParams(layoutParams);
            wFrostedBoard.setLayoutParams(layoutParams);
            wFrostedBoard2.setLayoutParams(layoutParams);

            //竖屏显示控件
            wTopRll.setVisibility(View.VISIBLE);

            //竖屏消失控件
            wLyRightFullScreenFunctionBtn.setVisibility(View.GONE);
            wRLFullScreenTimeRule.setVisibility(View.GONE);
            wLyCtvPullScreenPlaybackSpeed.setVisibility(View.GONE);
            wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
        } else {
            //隐藏虚拟按键
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);


            //横屏视屏播放宽高
            RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, screenWidth);
            textureView.setLayoutParams(layoutParams);
            wFrostedBoard.setLayoutParams(layoutParams);
            wFrostedBoard2.setLayoutParams(layoutParams);

            //横屏显示控件
            wLyRightFullScreenFunctionBtn.setVisibility(View.VISIBLE);
            wRLFullScreenTimeRule.setVisibility(View.VISIBLE);
            wLyCtvPullScreenPlaybackSpeed.setVisibility(View.VISIBLE);
            mAgainTag = true;
            startHideTimer();

            //横屏消失控件
            wTopRll.setVisibility(View.GONE);
            wRlPlaybackSpeed.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (task != null) {
            task.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
        wenMediaPlayerUtil.onDestoryMediaplayer();
    }

    @Override
    public void onBackPressed() {
        if (viewMode == MODE_LANDSPACE) {
            screenDisplay();
        } else {
            finish();
        }
    }

    //无视频展示界面
    private void noVideoView() {
        wTimeRuleView.setAlarmTimePartList(mAlarmlist);
        wTimeRuleView.setFullTimePartList(mFUlllist);
        wTimeRuleView.setCurrentTime(0);
        wFullScreenTimeRuleView.setAlarmTimePartList(mAlarmlist);
        wFullScreenTimeRuleView.setFullTimePartList(mFUlllist);
        wFullScreenTimeRuleView.setCurrentTime(0);
        TimerRuleRefresh();
        wenMediaPlayerUtil.onDestoryMediaplayer();
        wVideoProgressBar.setVisibility(View.GONE);
        wFrostedBoard2.setVisibility(View.VISIBLE);
    }

    public class HideHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FULL_SCREEN_WEIGHT:
                    mAgainTag = false;
                    //下移动画
                    TranslateAnimation moveDownAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 2.0f);
                    moveDownAnimation.setDuration(350);
                    //右移动画
                    TranslateAnimation moveRightAnimation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 2.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
                    moveRightAnimation.setDuration(350);

                    wLyRightFullScreenFunctionBtn.setVisibility(View.GONE);
                    wRLFullScreenTimeRule.setVisibility(View.GONE);
                    wLyCtvPullScreenPlaybackSpeed.setVisibility(View.GONE);

                    wCtvPlaybackSpeed.setChecked(false);
                    wCtvPullScreenPlaybackSpeed.setChecked(false);
                    wLyFullScreenPlaybackSpeed.setVisibility(View.GONE);
                    wRlPlaybackSpeed.setVisibility(View.GONE);

                    wLyRightFullScreenFunctionBtn.setAnimation(moveRightAnimation);
                    wRLFullScreenTimeRule.setAnimation(moveDownAnimation);
                    wLyCtvPullScreenPlaybackSpeed.setAnimation(moveDownAnimation);
                    break;
            }

        }
    }

    public void startHideTimer() {//开始计时,三秒后执行runable
        mHideHandler.removeCallbacks(hideRunable);
        mHideHandler.postDelayed(hideRunable, 3000);
    }

    public void endHideTimer() {//移除runable,将不再计时
        mHideHandler.removeCallbacks(hideRunable);
    }

    private Runnable hideRunable = new Runnable() {
        @Override
        public void run() {
            mHideHandler.obtainMessage(FULL_SCREEN_WEIGHT).sendToTarget();
        }
    };


    //保存截图
    public void saveBitmap(Bitmap bm, String fileName) {
        File appDir = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DCIM + File.separator + "Camera" + File.separator);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        fileName = fileName.substring(fileName.length() - 18, fileName.length());
        File pictureFile = new File(appDir, fileName);
        if (pictureFile.exists()) {
            pictureFile.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(pictureFile);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Snackbar.make(findViewById(android.R.id.content), getString(R.string.screenshot_saved_successfully) + pictureFile.getAbsolutePath(), Snackbar.LENGTH_SHORT).show();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(),
                    pictureFile.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(pictureFile);
        intent.setData(uri);
        sendBroadcast(intent);//这个广播的目的就是更新图库，发了这个广播进入相册就可以找到你保存的图片了！，记得要传你更新的file哦
    }


    // 下载具体操作，也可以使用sdk自带的下载方法
    private void download() {
        try {
            int count = 0;
            Log.d("当前视频", wenMediaPlayerUtil.getMediaPlayerIndex() + "");
            String mUrl = mVideoListQueue.get(wenMediaPlayerUtil.getMediaPlayerIndex());
            URL url = new URL(mUrl);
            // 下载后的文件名，自己定义
            if (mUrl != null) {
                fileName = dirName + mUrl.substring(mUrl.length()-10);
            }
            Log.d("url------>", url + "");
            File f = new File(fileName);
            if (!f.exists()) {
                //打开连接
                URLConnection conn = url.openConnection();
                totalSize = conn.getContentLength();
                //打开输入流
                is = conn.getInputStream();
                //创建字节流
                byte[] bs = new byte[1024];
                int len;
                os = new FileOutputStream(fileName);
                // 写数据
                while ((len = is.read(bs)) != -1) {
                    if (isCancle) {
                        f.delete();
                        os.close();
                        is.close();
                    }
                    os.write(bs, 0, len);
                    count += len;
                    handler.sendEmptyMessage(count);
                }

                // 完成后关闭流
                Log.e("视频下载", "download-finish");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
//                    progressDialog.dismiss();
                        wLyDownloadView.setVisibility(View.GONE);
                        Toast.makeText(CloudCameraHistoryPlaybackActivity.this, getString(R.string.download_completed), Toast.LENGTH_LONG).show();
                        wTvDownloadCount.setText("0.0%");
                    }
                });
                os.close();
                is.close();
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        wLyDownloadView.setVisibility(View.GONE);
                        Toast.makeText(CloudCameraHistoryPlaybackActivity.this, getString(R.string.file_already_exists), Toast.LENGTH_LONG).show();
                    }
                });
            }
        } catch (Exception e) {
//            progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (isCancle) {
                        isCancle = false;
                        wTvDownloadCount.setText("0.0%");
                    } else {
                        wTvDownloadCount.setText("0.0%");
                        Toast.makeText(CloudCameraHistoryPlaybackActivity.this, R.string.str_download_failed, Toast.LENGTH_LONG).show();
                        wLyDownloadView.setVisibility(View.GONE);
                    }
                }
            });
            e.printStackTrace();
            Log.e("视频下载", "e.getMessage() --- " + e.getMessage());
        }
    }


    //AlertDialog提示的进度框
    public void onDownload() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.dialog_title_prompt);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setMessage(R.string.downloading_video_prompt);
        builder.setPositiveButton(R.string.str_confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                progressDialog.show();
                wLyDownloadView.setVisibility(View.VISIBLE);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        download();
                    }
                }).start();
            }
        });
        builder.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(CloudCameraHistoryPlaybackActivity.this, R.string.cancel_download, Toast.LENGTH_LONG).show();
            }
        });
        builder.show();
    }

    private int totalSize;
    //设置进度条及文本
    @SuppressLint("HandlerLeak")
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            Log.d("进度", String.format("%.1f", msg.what * 1f / totalSize * 100));//保留一位小数点，且需注意数据在计算时应转为浮点型!
            wTvDownloadCount.setText(String.format("%.1f", msg.what * 1f / totalSize * 100) + "%");
        }
    };


    @Override
    protected void onStop() {
        super.onStop();
        if (wenMediaPlayerUtil.getMediaPlayer() != null) {
            wenMediaPlayerUtil.getMediaPlayer().pause();
            timeRuleViewTransparent.setVisibility(View.VISIBLE);
            wImbPlay.setSelected(true);
            wImbFullScreenPlay.setSelected(true);
        }
    }


    //是否播放声音
    public static Boolean getIsSound() {
        return wImSound.isSelected();
    }

    //添加测试数据
    private void addDate(){
        CloudHistoryPlayBackBean cloudHistoryPlayBackData = new CloudHistoryPlayBackBean();
        cloudHistoryPlayBackData.setMode(2);
        cloudHistoryPlayBackData.setEndDate("123020");
        cloudHistoryPlayBackData.setStartDate("122920");
        cloudHistoryPlayBackData.setUrl("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
        cloudHistoryPlayBackData.setLength(60);

        CloudHistoryPlayBackBean cloudHistoryPlayBackData1 = new CloudHistoryPlayBackBean();
        cloudHistoryPlayBackData1.setMode(2);
        cloudHistoryPlayBackData1.setEndDate("124120");
        cloudHistoryPlayBackData1.setStartDate("124020");
        cloudHistoryPlayBackData1.setUrl("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
        cloudHistoryPlayBackData1.setLength(60);

        mVideoDateList.add(cloudHistoryPlayBackData);
        mVideoDateList.add(cloudHistoryPlayBackData1);
        if (mVideoDateList.size() > 0) {
            for (int i = 0; i < mVideoDateList.size(); i++) {
                //添加循环视频播放数据
                mVideoListQueue.add(mVideoDateList.get(i).getUrl());
                TimeRuleView.TimePart part = new TimeRuleView.TimePart();
                part.startTime = TimestampToTimeDate.getStringDateToMillisecond(mVideoDateList.get(i).getStartDate());
                part.endTime = TimestampToTimeDate.getStringDateToMillisecond(mVideoDateList.get(i).getEndDate());
                if (1 == (mVideoDateList.get(i).getMode())) {
                    mFUlllist.add(part);
                } else {
                    mAlarmlist.add(part);
                }
                mAlllist.add(part);
            }
        }

        if (mVideoListQueue.size() > 0) {
            wenMediaPlayerUtil.initFirstPlayer(0, mVideoListQueue);
            wFrostedBoard.setOnClickListener(onClickListener);
            wVideoProgressBar.setVisibility(View.VISIBLE);
            wFrostedBoard.setVisibility(View.VISIBLE);
            wTimeRuleView.setAlarmTimePartList(mAlarmlist);
            wTimeRuleView.setFullTimePartList(mFUlllist);
            wFullScreenTimeRuleView.setAlarmTimePartList(mAlarmlist);
            wFullScreenTimeRuleView.setFullTimePartList(mFUlllist);
            TimerRuleRefresh();
        } else {
            wVideoProgressBar.setVisibility(View.GONE);
            wFrostedBoard2.setVisibility(View.VISIBLE);
            wFrostedBoard2.setText(R.string.current_time_no_video);
        }

        if (mAlllist.size() > 0) {
            wTimeRuleView.setCurrentTime(mAlllist.get(0).startTime);
            wFullScreenTimeRuleView.setCurrentTime(mAlllist.get(0).startTime);
        }
    }
}
